package com.leyou.gateway.filters;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @package com.leyou.gateway.filters
 * @description: 网关权限控制过滤器
 * @author: 许超越
 * @date 2019/7/9 16:23
 * @version: V1.0
 */
@Slf4j
@Component
public class AuthFilter extends ZuulFilter {

    @Autowired
    private JwtProperties prop;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private FilterProperties filterProp;

    /**
     * 过滤器类型
     *
     * @return
     */
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    /**
     * 过滤器执行时机
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return FORM_BODY_WRAPPER_FILTER_ORDER + 1;
    }

    /**
     * 设置过滤器开启的条件
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //获取上下文
        RequestContext cxt = RequestContext.getCurrentContext();
        //获取request
        HttpServletRequest request = cxt.getRequest();
        //获取请求的路径
        String path = request.getRequestURI();
        //判断路径是否在需要方行的路径下，放行false，过滤true
        return isAllowPath(path);
    }

    /**
     * 判断请求路径是是否符合方行条件
     * @param path
     * @return
     */
    private Boolean isAllowPath(String path) {
        //获取所有方行的路径遍历
        for (String allowPath : filterProp.getAllowPaths()) {
            //判断前缀是否匹配
            if (path.startsWith(allowPath)) {
                //一样方行
                return false;
            }
        }
        //不一样拦截
        return true;
    }

    /**
     * 过滤器具体过滤的逻辑
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取request请求
        HttpServletRequest request = ctx.getRequest();
        //获取token
        String token = CookieUtils.getCookieValue(request, prop.getUserTokenProperties().getCookieName());
        try {
            //解析token中的载荷信息
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
            //获取token的id判断是否已经过期
            Boolean bool = redisTemplate.hasKey(payload.getId());
            if (bool != null && bool) {
                //黑名单中存在token，无权访问
                throw new RuntimeException("用户已经登出，无效的token！");
            }
            //权限控制
            UserInfo userInfo = payload.getUserInfo();
            //获取用户权限
            String role = userInfo.getRole();
            //获取当前路径的资源和位置
            String path = request.getRequestURI();
            String method = request.getMethod();
            // TODO 判断权限，此处暂时空置，等待权限服务完成后补充
            log.info("【网关】用户{},角色{}。访问服务{} : {}，", userInfo.getUsername(), role, method, path);
        } catch (RuntimeException e) {
            //拦截请求
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(403);
            log.error("非法访问，未登录，地址：{}", request.getRemoteHost(), e);
        }
        return null;
    }
}
